﻿
namespace EasyStep.WinForms.Controls
{
    using System.Drawing;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using EasyStep.Data.Entities;
    using EasyStep.WinForms.Test;
    using EasyStep.Business.Interfaces;
    using EasyStep.TestEditor.Properties;
    using System.Runtime.InteropServices;


    public partial class TestDataEditor : UserControl
    {
        public ITestDataContext DataContext { get; set; }
        public const string constPrefix = "c:";
        public Color ValidDataBkColor = System.Drawing.SystemColors.Window;
        public Color NotValidDataBkColor = Color.Coral;
        private Button btnShowWizard;
        private TextBox txtSelectedValue;
        private TestData _Data;
        public AutoCompleteStringCollection AutoCompleteTexts { get; set; }
        public event EventHandler OnFocusLeave;
        public bool AutoConstantGeneration { get; set; }
        public TestData Data
        {
            get
            {
                return _Data;
            }
            set
            {
                _Data = value;
                UpdateEditor(_Data);
            }
        }


        private void UpdateEditor(TestData withData)
        {
            txtSelectedValue.AutoCompleteCustomSource = AutoCompleteTexts;
            if (withData == null) return;
            txtSelectedValue.Text = withData.Value;
            if (withData.Constant != null)
                txtSelectedValue.Text = string.Concat(constPrefix, withData.Constant.Name);
        }

        public void SetWatermark(string text)
        {
            SendMessage(txtSelectedValue.Handle, EM_SETCUEBANNER, 0, text);
        }

        public TestDataEditor()
        {
            InitializeComponent();
        }
        #region designer generated code
        private void InitializeComponent()
        {
            this.btnShowWizard = new System.Windows.Forms.Button();
            this.txtSelectedValue = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // btnShowWizard
            // 
            this.btnShowWizard.AutoSize = true;
            this.btnShowWizard.Dock = System.Windows.Forms.DockStyle.Right;
            this.btnShowWizard.FlatAppearance.BorderSize = 0;
            this.btnShowWizard.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnShowWizard.Font = new System.Drawing.Font("Microsoft Sans Serif", 6F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.btnShowWizard.Location = new System.Drawing.Point(298, 0);
            this.btnShowWizard.Name = "btnShowWizard";
            this.btnShowWizard.Size = new System.Drawing.Size(27, 20);
            this.btnShowWizard.TabIndex = 2;
            this.btnShowWizard.TabStop = false;
            this.btnShowWizard.Text = ". . .";
            this.btnShowWizard.UseVisualStyleBackColor = true;
            this.btnShowWizard.Click += new System.EventHandler(this.btnShowWizard_Click);
            this.btnShowWizard.MouseEnter += new System.EventHandler(this.BtnFlat_MouseEnter);
            this.btnShowWizard.MouseLeave += new System.EventHandler(this.BtnFlat_MouseLeave);
            // 
            // txtSelectedValue
            // 
            this.txtSelectedValue.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
            this.txtSelectedValue.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
            this.txtSelectedValue.CausesValidation = false;
            this.txtSelectedValue.Dock = System.Windows.Forms.DockStyle.Fill;
            this.txtSelectedValue.Location = new System.Drawing.Point(0, 0);
            this.txtSelectedValue.Name = "txtSelectedValue";
            this.txtSelectedValue.Size = new System.Drawing.Size(325, 20);
            this.txtSelectedValue.TabIndex = 1;
            this.txtSelectedValue.TextChanged += new System.EventHandler(this.Ensure_ConstantData);
            this.txtSelectedValue.DoubleClick += new System.EventHandler(this.txtSelectedValue_DoubleClick);
            this.txtSelectedValue.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.txtSelectedValue_PreviewKeyDown);
            // 
            // TestDataEditor
            // 
            this.Controls.Add(this.btnShowWizard);
            this.Controls.Add(this.txtSelectedValue);
            this.Name = "TestDataEditor";
            this.Size = new System.Drawing.Size(325, 20);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private void Ensure_ConstantData(object sender, EventArgs e)
        {
            var cntrl = sender as TextBox;
            if (!(cntrl.AutoCompleteCustomSource == null || cntrl.AutoCompleteCustomSource.Count == 0)) return;
            //if (!cntrl.Text.StartsWith(constPrefix)) return;

            cntrl.AutoCompleteCustomSource.Clear();
            var data = DataContext.ConstantsManager.GetAll()
                .Select(i => string.Concat(constPrefix, i.Name))//+consts list
                .OrderBy(i => i)
                .Union(DataContext.TestInfoManager.GetProjectTests().OrderBy(t => t.Name).Select(t => t.Name))//+projects list
                .ToArray();
            if (data.Length>0)
                cntrl.AutoCompleteCustomSource.AddRange(data);
        }

        private void btnShowWizard_Click(object sender, EventArgs e)
        {
            var constPicker = new ConstantPicker(DataContext);
            constPicker.Shown += new EventHandler((s, et) =>
            {
                var withPrefix = ((txtSelectedValue.Text ?? "").StartsWith(constPrefix));
                var key = withPrefix ? txtSelectedValue.Text.Remove(0, constPrefix.Length) : txtSelectedValue.Text;
                var constant = withPrefix && !string.IsNullOrEmpty(key)? DataContext.ConstantsManager.Get(key) : null;

                constPicker.Key = constant != null ? constant.Name : key;
                constPicker.Value = constant != null ? constant.Value : key;
            });
            if (constPicker.ShowDialog() == DialogResult.OK)
                txtSelectedValue.Text = string.Concat(constPrefix, constPicker.Key);

        }


        public bool ValidateData()
        {

            var result = !string.IsNullOrEmpty(txtSelectedValue.Text);
            Data = new TestData() { Value = (txtSelectedValue.Text ?? "").Trim() };
            if (Data.Value.StartsWith(constPrefix))
            {
                var cname = txtSelectedValue.Text.Remove(0, constPrefix.Length);
                Data.Constant = DataContext.ConstantsManager.Get(cname);
                if (Data.Constant != null) Data.ConstId = Data.Constant.Id;
                else
                {
                    if (AutoConstantGeneration || MessageBox.Show("Do you want automatically generate constant with name: " + cname + "?", "Save Constant Dialog", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Data.Constant = DataContext.ConstantsManager.GetOrCreateConst(cname, cname, Guid.Empty);
                        if (Data.Constant != null) Data.ConstId = Data.Constant.Id;
                    }
                }
            }
            txtSelectedValue.BackColor = result ? ValidDataBkColor : NotValidDataBkColor;
            return result;
        }



        private void txtSelectedValue_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if ((e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab) && Settings.Default.CreateNewStepByTab && OnFocusLeave != null)
                OnFocusLeave(sender, e);
        }

        private void txtSelectedValue_DoubleClick(object sender, EventArgs e)
        {
            btnShowWizard_Click(sender, e);
        }

        private void BtnFlat_MouseEnter(object sender, EventArgs e)
        {
            var BtnFlat = sender as Button;
            BtnFlat.FlatAppearance.BorderSize = 1;
            BtnFlat.FlatStyle = System.Windows.Forms.FlatStyle.Standard;
        }
        private void BtnFlat_MouseLeave(object sender, EventArgs e)
        {
            var BtnFlat = sender as Button;
            BtnFlat.FlatAppearance.BorderSize = 0;
            BtnFlat.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        }

        private const uint ECM_FIRST = 0x1500;
        private const uint EM_SETCUEBANNER = ECM_FIRST + 1;

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);


        
    }

}
